<?php

/**
 * @Author: lujizhang
 * @Date:   2019-10-16 09:26:11
 * @Last Modified by:   lujizhang
 * @Last Modified time: 2019-11-04 10:37:36
 */

namespace app\api\model;
use think\Db;

class WechatThird {
    public $component_appid='';
    public $component_access_token = '';
    public $component_app_secret = '';
    public $component_msg_token = '';
    public $component_msg_aeskey = '';
    public $component_verify_ticket='';
    public $wxApiBase = "https://api.weixin.qq.com/cgi-bin";
    public $callBackUrl = "/api/wechat/messageEvent";
    public $preAuthBackUrl = "/api/wechat/preAuthBack";
    
    function __construct(){
        
        $wx_config = Db::table('sy_wx_config')->where('status=1')->order('id desc')->find();
        $this->wx_config = $wx_config;

        if(!empty($wx_config)){
            $this->component_appid = $wx_config['wx_app_id'];
            $this->component_app_secret = $wx_config['wx_app_secret'];
            $this->component_msg_token = $wx_config['wx_msg_token'];
            $this->component_msg_aeskey = $wx_config['wx_msg_aeskey'];
            $this->component_verify_ticket = $wx_config['component_verify_ticket'];
            $this->component_access_token = $wx_config['access_token'];
            $this->callBackUrl = $wx_config['callback_url'];
            $this->preAuthBackUrl = $wx_config['preauth_back_url'];
        }
        else{
            subLog('没有配置微信参数','Wechat __construct');
        }
    }

    public function getComponentAccessTokenFromWechat(){
        $url=$this->wxApiBase."/component/api_component_token";
        $data = [
            'component_appid'=>$this->component_appid,
            'component_appsecret'=>$this->component_app_secret,
            'component_verify_ticket'=>$this->component_verify_ticket
        ];
        
        $res = $this->httpRequest($url,$data);
        $content = json_decode($res,true);
        // var_dump($content);die();
        if(!empty($content['component_access_token'])){
            
            $access_token = $content['component_access_token'];
            $expires_in = $content['expires_in'];
            $this->component_access_token = $access_token;
            // 更新获取状态
            $status = 2;
            $this->updateGetTokenStatus($status);
            return $access_token;
        }
        else{
            var_dump($content);
        }
        
    }

    public function getPreAuthCode(){
        $url =$this->wxApiBase.'/component/api_create_preauthcode?component_access_token='.$this->component_access_token;
        $data = [
            'component_appid'=>$this->component_appid
        ];
        $res = $this->httpRequest($url,$data);
        
        $content = json_decode($res,true);
        return $content;
    }

    /**
     * 使用授权码获取授权信息
     */
    public function queryAuth($authCode){
        $url =$this->wxApiBase.'/component/api_query_auth?component_access_token='.$this->component_access_token;
        $data = [
            'component_appid'=>$this->component_appid,
            'authorization_code'=>$authCode
        ];
        $res = $this->httpRequest($url,$data);
        
        $content = json_decode($res,true);
        if(!empty($content['authorization_info'])) return $content;
        else {
            subLog($res,'queryAuth failed','wechat');
            return false;
        }
        
    }
    
    /**
     * 从数据库获取当前保存的token
     * @return [type] [description]
     */
    public function getTokenFromDb(){
        $component_access_token = Db::table('sy_wx_config')
            ->where('wx_app_id="'.$this->component_appid.'" ')
            ->order('id desc')
            ->value('access_token');
        return $access_token;
    }

    /**
     * 更新获取token状态
     * @param  [type] $status [description]
     * @return [type]         [description]
     */
    public function updateGetTokenStatus($status){
        $n = 0;
        if($status == 1){
            $n = Db::table('sy_wx_config')
                ->where('wx_app_id="'.$this->component_appid.'" and get_token_status!=1')
                ->update(['get_token_status'=>1]);
        }
        else{
            $expired = date("Y-m-d H:i:s",time()+7200);
            $n = Db::table('sy_wx_config')
                ->where('wx_app_id="'.$this->component_appid.'" ')//and get_token_status=1
                ->update(['get_token_status'=>2,
                'access_token'=>$this->component_access_token,
                'token_expired'=>$expired,
                ]);
        }
        return $n;
    }

     /**
     * @return mixed
     * {
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }
        由于 access_token 拥有较短的有效期，当 access_token 超时后，
        可以使用 refresh_token 进行刷新，refresh_token 拥有较长的有效期（30 天），
        当 refresh_token 失效的后，需要用户重新授权。
     */
    public function getOauthTokenByThird($appId,$code){

        $api_url = $this->wxSnsApiBase."/oauth2/component/access_token".
            "?appid=".$appId.
            "&code=".$code.
            "&grant_type=authorization_code".
            "&component_appid=".$this->component_appid.
            "&component_access_token=".$this->component_access_token;
        
        $weixin_return = $this->httpRequest($api_url);
        subLog($weixin_return,'oauth token'.$api_url);
        return $weixin_return;
    }

    public function refreshOauthTokenByThird($appId,$code){
        $api_url = $this->wxSnsApiBase."/oauth2/component/refresh_token".
            "?appid=".$appId.
            "&refresh_token=".$refreshToken.
            "&grant_type=refresh_token".
            "&component_appid=".$this->component_appid.
            "&component_access_token=".$this->component_access_token;
        $weixin_return = $this->httpRequest($api_url);
        subLog($weixin_return,'oauth refresh token'.$api_url);
        return $weixin_return;
    }

    public function encryptUrl($url){
        $aes = new Aes;
        $url = $aes->encrypt($url);
        $url = urlencode($url);
        return $url;
    }

    function httpRequest($url,$data = null,$responseHeader = false){
        $curl = curl_init();
       
        curl_setopt($curl, CURLOPT_HEADER,$responseHeader);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        if(\is_array($data)) $data = \json_encode($data,JSON_UNESCAPED_UNICODE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
        $output = curl_exec($curl);
        curl_close($curl);
        //subLog("weixinapi====".$url,$output);
        return $output;
    }

}
